﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Chirpr Settings</title>
	<link rel="stylesheet" type="text/css" href="css/default.css" />
	<script src="js/jquery.js" type="text/javascript"></script>
	<script src="js/util.js"   type="text/javascript"></script>
	<script src="js/chirpr.js" type="text/javascript"></script>
	<script type="text/javascript">//<![CDATA[
	/***************************************************************************
	 * Settings Page                              http://www.codeplex.com/chirpr
	 *                                          Microsoft Public License (Ms-PL)
	 * Authors
	 *  - Charles Schmidt   2007-08  http://www.pickelhau.be
	 *  - Michael Flanakin  2008-10  http://www.michaelflanakin.com
	 *
	 * page
	 *  - checkCredentials : validates the credentials against twitter
	 *  - init             : initializes the page
	 *  - isValid          : validates settings
	 *  - regions          : functions to create, open, and close regions
	 **************************************************************************/
	var page =
	{
		//***| controls |*******************************************************

		uid          : null,
		pwd          : null,
		snd          : null,
		info         : null,
		debugButtons : null,

			
		//***| initializes the page |*******************************************

		init: function()
		{
			// log
			chirpr.logSettings("settings", "[dialog session]", gadget.logging.entryPoint);
			chirpr.logSettings("settings", "page.init", gadget.logging.entryPoint);
			
			// load controls
			page.region       = $('#region')[0];
			page.regionHead   = $('#regionHead')[0];
			page.menu         = $('#menu')[0];
			page.uid          = $('userName')[0];
			page.pwd          = $('password')[0];
			page.snd          = $('notifySound')[0];
			page.enableLog    = $('enableLog')[0];
			page.info         = $('info')[0];
			page.debugButtons = $('debug:buttons')[0];
			
			// get properties
			chirpr.logSettings("settings", "page.init", "get current settings");
			if (!util.string.isEmpty(chirpr.userName)) { page.uid.value = chirpr.userName; }
			if (!util.string.isEmpty(chirpr.password)) { page.pwd.value = chirpr.password; }
			page.enableLog.checked = gadget.logging.enabled;
			if (!util.string.isEmpty(chirpr.notifySound))
			{
				for (var i=0; i<page.snd.options.length; i++)
				{
					if (page.snd.options[i].value == chirpr.notifySound)
					{
						page.snd.selectedIndex = i;
						break;
					}
				}
			}
			
			// attach event handler
			if (gadget.host.browser)
			{
				chirpr.logSettings("settings", "page.init", "show debug");
				page.debugButtons.style.display = 'block';
			}
			else
			{
				chirpr.logSettings("settings", "page.init", "set ok/cancel handler");
				System.Gadget.onSettingsClosing = page.settingsClosing;
			}
			
			// init regions
			page.regions.init();
			
			// if no credentials, default to cred screen
			if (!chirpr.hasCredentials()) { chirpr.logSettings("settings", "page.init", "no creds, open creds region"); $('#credsLink')[0].onclick(); }
			
			// exit
			chirpr.logSettings("settings", "page.init", gadget.logging.exitPoint);
		},
		

		//***| checks the current settings to see if they are valid |***********
		
		isValid: function()
		{
			if (util.string.isEmpty(page.uid.value) || util.string.isEmpty(page.pwd.value))
			{
				page.info.style.display = "block";
				page.info.className     = "error";
				page.info.innerText     = "Umm... you forgot something. I need your Twitter credentials.";
				return false;
			}
			return true;
		},
		
		
		//***| checks the currently saved credentials |*************************

		checkCredentials: function()
		{
			// username/password required
			page.info.style.display = "block";
			page.info.innerText     = "Checking your credentials, now...";
			if (!page.isValid()) { return; }
			
			// sign out/in
			chirpr.twitter.signOut();
			var isSuccessful = chirpr.twitter.signIn(page.uid.value, page.pwd.value);
			
			// show status
			page.info.className = (isSuccessful ? "note" : "error");
			page.info.innerText = (isSuccessful ? "Yep, it's working!" 
				: "Oops... did you mistype something? Twitter didn't recognize this user.");
		},
	

		//***| handles the ok and cancel button click |*************************
		
		settingsClosing: function(event)
		{
			// hide/clear error
			page.info.style.display = "none";
			page.info.innerText     = "";

			// if committing, save settings; otherwise, do nothing
			if (event.closeAction == event.Action.commit)
			{
				// check for valid settings
				if (!page.isValid()) { event.cancel = true; return; }

				// save properties
				chirpr.properties.setUserName(page.uid.value);
				chirpr.properties.setPassword(page.pwd.value);
				chirpr.properties.setNotifySound((page.snd.options.selectedIndex == 0) ? "" : page.snd.options[page.snd.selectedIndex].value);
				gadget.logging.setEnabled(page.enableLog.checked);
			}
			event.cancel = false;
			
			// collapse checkpoint for entire settings session
			chirpr.logSettings("settings", "[dialog session]", gadget.logging.exitPoint, true, 
				(event.closeAction == event.Action.commit) ? "settings saved" : "cancelled; no change");
			
			// close window, if in browser
			if (gadget.host.browser) { window.close(); }
		},


		/***********************************************************************
		 * page.regions
		 *  - register : registers a new region
		 *  - open     : opens a region
		 *  - close    : closes a region
		 **********************************************************************/
		regions:
		{
			init: function()
			{
				chirpr.logSettings("settings", "page.regions.init", gadget.logging.entryPoint);
				page.regions.register("creds", "Twitter Credentials", 
					function()
					{
						chirpr.logSettings("settings", "page.regions.init[creds.load]", "load credentials region");
						$('#userName').focus();
					});
				page.regions.register("log", "Troubleshooting",
					function()
					{
						chirpr.logSettings("settings", "page.regions.init[log.load]", "load log region");
						var successCount = 0;
						var failureCount = 0;
						for (var i=0; i<gadget.logging.history.length; i++)
						{
							if (gadget.logging.history[i].successful) { successCount++; }
							else { failureCount++; }
						}
						$('#logSuccessMessage').text(successCount + ' success' + ((successCount == 1) ? '' : 'es'));
						$('#logFailureMessage').text(failureCount + ' failure' + ((failureCount == 1) ? '' : 's'));
						if(failureCount == 0){ $('#logFailureMessage,#logHasFailures').hide(); }
						else{ $('#logFailureMessage,#logHasFailures').show(); }
						$('#logStart').text( (gadget.logging.history.length == 0) ? "chirpr started"
							: util.date.toLongDateString(gadget.logging.history[0].date) + " at " + util.date.toTimeString(gadget.logging.history[0].date) );
						$('#logLoader').click(function()
						{
							var html = "<ol>";
							for (var i=gadget.logging.history.length-1; i>=0; i--)
							{
								var item = gadget.logging.history[i];
								var unknownAction = "s";
								var actionChars = new Array();
								actionChars[gadget.logging.actions.init]            = "~";
								actionChars[gadget.logging.actions.javascriptError] = "ê";
								actionChars[gadget.logging.actions.logging]         = "¤";
								actionChars[gadget.logging.actions.saveSettings]    = "@";
								actionChars[gadget.logging.actions.authenticate]    = "Ñ";
								actionChars[gadget.logging.actions.getMessages]     = "_";
								actionChars[gadget.logging.actions.postMessage]     = ")";
								actionChars[gadget.logging.actions.followUser]      = "Y";
								html += "<li class='{8}'><div class='action accentchars web'><span title='{0}'>{1}</span><span title='{4}'>{5}</span><span class='wing1' title='{9}'>{10}</span></div><div class='date'>{6}</div><div><span class='page'>{2}</span><span class='function'>{3}</span></div><div class='desc'>{7}</div><div class='outcome'>{11}</div></li>"
									.replace("{0}", ((util.string.isEmpty(item.user) || item.user=="anon") ? "Anonymous" : item.user))
									.replace("{1}", ((util.string.isEmpty(item.user) || item.user=="anon") ? "Ð" : "Ï"))								
									.replace("{2}", item.page)
									.replace("{3}", item.func)								
									.replace("{4}", gadget.logging.actions.toString(item.action))
									.replace("{5}", (item.action < 0 || item.action >= actionChars.length || util.string.isEmpty(actionChars[item.action])) ? unknownAction : actionChars[item.action])
									.replace("{6}", util.date.toShortDateTimeString(item.date))
									.replace("{7}", item.description)
									.replace("{8}", (item.successful ? "success" : "failed"))
									.replace("{9}", (item.successful ? "Succeeded" : "Failed"))
									.replace("{10}", (item.successful ? "ü" : "û"))
									.replace("{11}", (util.string.isEmpty(item.outcome) ? "" : "<div class='outcome'>"+item.outcome+"</div>"));
							}
							html += "</ol>";
							$('#logTable').html(html);
						});
					});
				$('#sendError').click(function()
				{
					var err = "";
					for (var i=0; i<gadget.logging.history.length; i++)
					{
						err += "\n" + gadget.logging.formatEntry(gadget.logging.history[i]);
					}
					var textarea = document.createElement("textarea");
					textarea.innerText = err;
					try{textarea.createTextRange().execCommand('copy');}catch(e){/*ignore*/}
				});
					
				// about
				page.regions.register("about", "About "+gadget.name,  
					function()
					{
						chirpr.logSettings("settings", "page.regions.init[about.load]", "load about region");
						$('#gadgetName').text(gadget.name + " v" + gadget.version);
					});
					
				// exit
				chirpr.logSettings("settings", "page.regions.init", gadget.logging.exitPoint);
			},
			
			register: function(id, text, startup)
			{
				var img         = document.createElement("img");
				img.id          = id+"Button";
				img.alt         = text;
				img.src         = "img/"+id+".png";
				img.onmouseover = function(){util.opacity.darkenMore(this);};
				img.onmouseout  = function(){util.opacity.lightenLess(this);};
				util.opacity.lightenLess(img);
				
				var a     = document.createElement("a");
				a.id      = id+"Link";
				a.href    = "javascript:";
				a.onclick = function(){page.regions.open(id, text, startup);};
				a.appendChild(img);
				
				var div   = document.createElement("div");
				div.className = "button";
				div.appendChild(a);
				
				page.menu.appendChild(div);
			},
			
			open: function(id, text, startup)
			{
				var img = document.createElement("img");
				img.src = "img/"+id+"_16x.png";
				img.alt = text;
				
				var a = document.createElement("a");
				a.className = "arrow";
				a.href      = "javascript:";
				a.title     = "Save & Return";
				a.onclick   = function(){page.regions.close(id);};
				a.innerText = "ç";
				
				page.regionHead.innerText = ""; // clears body
				page.regionHead.appendChild(img);
				page.regionHead.appendChild(a);
				page.regionHead.appendChild(document.createTextNode(text));
				
				page.menu.style.display   = "none";
				page.region.style.display = "block";
				$('#'+id+'Region').show();

				// startup
				startup();
			},
			
			close: function(id)
			{
				page.menu.style.display    = "";
				page.region.style.display = "";
				$('#'+id+'Region')[0].style.display = "";
			}
		}
	};
	</script>
</head>
<body id="settings">

	<div id="menu"></div>
	
	<div id="region">
		<h1 id="regionHead"></h1>
		
		<div id="credsRegion" class="region">
			<div class="formrow">
				<a class="info" href="https://twitter.com/signup" tabindex="1"><span class="hidden">create new</span> <span class="accentchar wing1">ä</span></a>
				<label for="userName">username</label>
				<input id="userName" class="required" tabindex="2" type="text"/>
			</div>
			<div class="formrow">
				<a class="info" id="testConnection" href="javascript:page.checkCredentials();" tabindex="4"><span class="hidden">verify account</span> <span class="accentchar wing1">ü</span></a>
				<label for="password">password</label>
				<input id="password" class="required" tabindex="3" type="password"/>
			</div>
			<div class="formrow">
				<bgsound id="sound" />
				<a class="info" href="http://www.codeplex.com/chirpr/Wiki/View.aspx?title=New%20Message%20Notification&referringTitle=Home" tabindex="6"><span class="hidden">our sounds</span> <span class="accentchar wing1">ä</span></a>
				<label for="notifySound">new message alert</label>
				<select id="notifySound" tabindex="5" onchange="if (this.selectedIndex>0) { var s=$('#sound')[0]; s.src=this.options[this.selectedIndex].value; try {s.play();} catch(e) {} }">
					<option value="">no, thanks</option>
					<option value="sounds/canary1.wav">canary (1)</option>
					<option value="sounds/canary2.wav">canary (2)</option>
					<option value="sounds/canary3.wav">canary (3)</option>
					<option value="sounds/cardinal1.wav">cardinal (1)</option>
					<option value="sounds/cardinal2.wav">cardinal (2)</option>
					<option value="sounds/meadowlark.wav">meadowlark</option>
					<option value="sounds/songsparrow.wav">song sparrow</option>
					<option value="sounds/woodthrush.wav">wood thrush</option>
				</select><br/>
			</div>
			<div class="formrow">
				<input id="enableLog" type="checkbox" style="float:right;"/>
				<label for="enableLog">enable logging</label>
				<div style="clear:both; color:#666; font-size:.9em; font-style:italic; text-align:center;">
					log for troubleshooting only; view/clear
					from <u>Settings > Troubleshooting</u>
				</div>
			</div>
			<div id="info"></div>
		</div>
		
		<div id="logRegion" class="region">
			<div>
				<span id="logSuccessMessage">No log entries</span>
				<span id="logHasFailures" style="display:none;">and
				</span><span id="logFailureMessage"></span>
				&nbsp;since <span id="logStart">Chirpr started</span>.
			</div>
			<div id="logTable">
				<div id="logSplash">
					<a id="logLoader" href="javascript:">Show Log <span class="wing1">¸</span></a>
					log may take several<br/>minutes to load, if there<br/>are a lot of entries
				</div>
			</div>
			<a id="sendError" href="http://www.codeplex.com/chirpr/Wiki/View.aspx?title=Troubleshooting" style="float:left;"><span class="accentchar wing1">ß</span> get help</a>
			<a href="javascript:gadget.logging.clear(); $('#logLink').click();" style="float:right;">clear all <span class="accentchar wing1">Ö</span></a>
		</div>
		
		<div id="aboutRegion" class="region">
			<h2 id="gadgetName"></h2>
			<div><a href="http://codeplex.com/chirpr" title="Discussions, bug reports, feature requests, and pre-release downloads">codeplex.com/chirpr <span class="accentchar wing1">ä</span></a></div>
			<div>
				<a href="http://twitter.com/chirpr" title="Chirpr on Twitter">Twitter / chirpr <span class="accentchar wing1">ä</span></a>
				<!--a class="accentchar wing2" href="javascript:chirpr.twitter.follow('chirpr');" title="Follow Chirpr on Twitter">Ë</a--><br/>
			</div>
			<div>
				<a href="http://www.pickelhau.be">Charles Schmidt <span class="accentchar wing1">ä</span></a>
				<!--a class="accentchar wing2" href="javascript:chirpr.twitter.follow('tatertoten');" title="Follow Charles on Twitter">Ë</a--><br/>
				<a href="http://www.michaelflanakin.com">Michael Flanakin <span class="accentchar wing1">ä</span></a>
				<!--a class="accentchar wing2" href="javascript:chirpr.twitter.follow('flanakin');" title="Follow Michael on Twitter">Ë</a-->
			</div>
		</div>
	</div>

			
	<p id="debug:buttons" class="debug">
		<button onclick="page.settingsClosing({Action:{cancel:0,commit:1},cancel:false,closeAction:1});">OK</button>
		<button onclick="page.settingsClosing({Action:{cancel:0,commit:1},cancel:false,closeAction:0});">Cancel</button>
	</p>

</body>
</html>
